package com.run.common.utils;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URISyntaxException;
import java.util.*;

public class HttpUtils {

    public static HttpResponse doPost(String host, String path,
                                      Map<String, String> headers) throws IOException {
        HttpPost httpPost = new HttpPost(host + path);
        //拼接参数
        List<NameValuePair> nvps = new ArrayList<>();
        Iterator<String> iterator = headers.keySet().iterator();
        while (iterator.hasNext()) {
            String key = iterator.next();
            nvps.add(new BasicNameValuePair(key, headers.get(key)));
        }
        try {
            httpPost.setEntity(new UrlEncodedFormEntity(nvps));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } finally {
            return HttpClientBuilder.create().build().execute(httpPost);
        }
    }

    public static HttpResponse doGet(String host, String path,
                                     Map<String, String> headers) throws IOException, URISyntaxException {
        URIBuilder uriBuilder = null;
        List<NameValuePair> nvps = new ArrayList<>();
        Iterator<String> iterator = headers.keySet().iterator();
        while (iterator.hasNext()) {
            String next = iterator.next();
            nvps.add(new BasicNameValuePair(next, headers.get(next)));//参数
        }
        uriBuilder = new URIBuilder(host + path);
        //可以加很多参数
        uriBuilder.setParameters(nvps);
        HttpGet httpGet = new HttpGet(uriBuilder.build());
        return HttpClientBuilder.create().build().execute(httpGet);//CloseableHttpClient执行方法
    }


}
